package cn.com.nes.site.service.monitor.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.*;
import cn.com.nes.common.util.id.IdUtils;
import cn.com.nes.mybatis.agent.monitor.entity.IsSystemStandardField;
import cn.com.nes.mybatis.agent.monitor.entity.ProtocolDataItemMemory;
import cn.com.nes.mybatis.agent.monitor.mapper.IsSystemStandardFieldMapper;
import cn.com.nes.mybatis.agent.monitor.mapper.ProtocolDataItemMemoryMapper;
import cn.com.nes.mybatis.agent.ope.entity.GGoods;
import cn.com.nes.mybatis.agent.ope.entity.IsEquipmentInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsManufactureInfo;
import cn.com.nes.mybatis.agent.ope.entity.Sblx;
import cn.com.nes.mybatis.agent.ope.mapper.IsDeviceProtocolDataItemInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsEquipmentInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.XzqhMapper;
import cn.com.nes.mybatis.agent.system.entity.Company;
import cn.com.nes.mybatis.agent.system.mapper.TAgentFacturerMapper;
import cn.com.nes.mybatis.clickhouse.mapper.IsNormDataHisBufferMapper;
import cn.com.nes.site.entity.OtherData;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.bo.workorder.SaveWorkOrderEquipmentInfoBO;
import cn.com.nes.site.entity.dto.fault.SysbListDto;
import cn.com.nes.site.entity.dto.monitor.GetFieldDtoListDto;
import cn.com.nes.site.entity.dto.monitor.GetLastHisDateBySbIDDto;
import cn.com.nes.site.entity.dto.product.GGoodsDTO;
import cn.com.nes.site.entity.em.CompanyTypeEnum;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.vo.fault.FaultVo;
import cn.com.nes.site.entity.vo.monitor.BrandVo;
import cn.com.nes.site.entity.vo.monitor.GetEquipmentInfoOperationConditionHistoryVo;
import cn.com.nes.site.entity.vo.monitor.SavePersonalProtocolDataToMemoryVo;
import cn.com.nes.site.service.crm.order.SalePriceService;
import cn.com.nes.site.service.crm.order.dto.SalePriceDetailDTO;
import cn.com.nes.site.service.crm.order.dto.SalePriceMasterDTO;
import cn.com.nes.site.service.monitor.EquipmentService;
import cn.com.nes.site.service.monitor.bo.EquipmentBO;
import cn.com.nes.site.service.monitor.dto.EquipmentDTO;
import cn.com.nes.site.service.monitor.dto.EquipmentInfoDTO;
import cn.com.nes.site.service.product.GGoodsService;
import cn.com.nes.site.service.product.SblxService;
import cn.com.nes.site.service.system.company.BusinessCompanyService;
import cn.com.nes.site.service.system.company.ManufactureService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EquipmentServiceImpl extends ServiceImpl<IsEquipmentInfoMapper, IsEquipmentInfo> implements EquipmentService {

    @Resource
    private TAgentFacturerMapper tAgentFacturerMapper;

    @Resource
    private XzqhMapper xzqhMapper;

    @Resource
    private ProtocolDataItemMemoryMapper protocolDataItemMemoryMapper;

    @Resource
    private IsDeviceProtocolDataItemInfoMapper isDeviceProtocolDataItemInfoMapper;

    @Resource
    private IsNormDataHisBufferMapper isNormDataHisBufferMapper;

    @Resource
    private IsSystemStandardFieldMapper isSystemStandardFieldMapper;

    @Resource
    private SalePriceService salePriceService;

    @Resource
    private GGoodsService gGoodsService;

    @Resource
    SblxService sblxService;

    @Resource
    ManufactureService manufactureService;

    @Resource
    BusinessCompanyService businessCompanyService;

    @Override
    public List<Map<String, Object>> getBrand(BrandVo vo) throws Exception {
        return tAgentFacturerMapper.getBrand(vo.getUserInfo().getCompanyId());
    }

    @Override
    public PageData getHistoricalFaultSbList(FaultVo vo) {

        //处理起止日期
        Map<String, Date> timeMap = TimeUtils.handleTimeSpan(vo.getStartTime(), vo.getEndTime(), 30 * 24 * 60 * 60 * 1000L);
        vo.setStartTime(timeMap.get("startTime"));
        vo.setEndTime(timeMap.get("endTime"));

        String userXzqh = vo.getUserInfo().getAreacode();
        if (StringUtils.isBlank(userXzqh)) {
            userXzqh = "86";
        }
        //获取当前用户的行政区划级别
        String permissionLevel = xzqhMapper.getXzqhJb(userXzqh);
        //获取传入的行政区划查询条件的行政区划级别
        String level = xzqhMapper.getXzqhJb(vo.getSsxzqh());
        //实际将要查询的行政区划条件
        String ssxzqh = XzqhUtils.comparePermission(userXzqh, vo.getSsxzqh(), permissionLevel, level);
        vo.setSsxzqh(ssxzqh);
        Page<SysbListDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<SysbListDto> sysbListDtos = this.baseMapper.getHistoricalFaultSbList(page, vo);
        return PageData.ok(page, sysbListDtos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData savePersonalProtocolDataToMemory(SavePersonalProtocolDataToMemoryVo vo) {
        //通过协议id与登录用户id 先删除，再新增
        protocolDataItemMemoryMapper.delete(new QueryWrapper<ProtocolDataItemMemory>().eq(ProtocolDataItemMemory.PROTOCOL_ID, vo.getProtocolId())
                .eq(ProtocolDataItemMemory.USER_ID, vo.getOperateUserId()));
        ProtocolDataItemMemory protocolDataItemMemory = new ProtocolDataItemMemory();
        protocolDataItemMemory.setUserId(vo.getOperateUserId());
        protocolDataItemMemory.setProtocolId(vo.getProtocolId());
        protocolDataItemMemory.setCodes(vo.getDataitems());
        protocolDataItemMemory.setGmtCreateId(vo.getOperateUserId());
        protocolDataItemMemoryMapper.insert(protocolDataItemMemory);
        return PageData.ok();
    }

    @Override
    public PageData getEquipmentInfoOperationConditionHistory(GetEquipmentInfoOperationConditionHistoryVo vo) {
        PageData res = new PageData();
        //获取设备历史数据 指定时间
        if (StringUtils.isEmpty(vo.getStartTime())) {
            String[] date = getLastHisDateBySbID(vo.getSbId(), "2");
            vo.setStartTime(date[0]);
            vo.setEndTime(date[1]);
        }

        //查询数据项 对勾数据
        Map<String, Object> protocolDataItem = getProtocolDataItem(vo.getProtocolId(), vo.getOperateUserId());

        // 显示值上下限
        Map<String, BigDecimal> showDataItem_up = new HashMap<>();
        Map<String, BigDecimal> showDataItem_low = new HashMap<>();

        //获取字段分类
        List<GetFieldDtoListDto> fieldDtoList = isDeviceProtocolDataItemInfoMapper.getFieldDtoList(vo);
        List<Map<String, Object>> classifyDtoList = new ArrayList<>();
        for (GetFieldDtoListDto getFieldDtoListDto : fieldDtoList) {

            showDataItem_up.put(getFieldDtoListDto.getDataItem(), getFieldDtoListDto.getShowRangeUp());
            showDataItem_low.put(getFieldDtoListDto.getDataItem(), getFieldDtoListDto.getShowRangeLow());

            //如果可以找到 则打对勾
            String value = (String) protocolDataItem.get(getFieldDtoListDto.getDataItem());
            if (value != null) {
                getFieldDtoListDto.setIsShowTick(true);
            } else {
                getFieldDtoListDto.setIsShowTick(false);
            }
            //判断单位值名称是否为空
            if (StrUtil.isEmpty(getFieldDtoListDto.getUnitValueName())) {
                getFieldDtoListDto.setIsShowData(false);
            } else {
                getFieldDtoListDto.setIsShowData(true);
            }
            Map<String, Object> e = new LinkedHashMap<>();
            e.put("classifyId", getFieldDtoListDto.getClassifyId());
            e.put("classifyName", getFieldDtoListDto.getClassifyName());
            if (!classifyDtoList.contains(e)) {
                classifyDtoList.add(e);
            }
        }

        //获取历史数据
        List<Map<String, Object>> dataList = isNormDataHisBufferMapper.getEquipmentConditionHistory(vo);
        res.setRecordcount(dataList.size());
        if (!"2".equals(vo.getDataType())) {
            dataList = DBUitl.paginate(dataList, vo.getPageid(), vo.getPagesize());
        }
        for (Map<String, Object> mapData : dataList) {
            String other_data = (String) mapData.get("other_data");
            mapData.put("other_data", null);
            List<OtherData> otherDataList = ZipUtils.processOtherData(other_data);
            for (OtherData otherData : otherDataList) {
                String f = otherData.getF();
                BigDecimal value = null;
                try {
                    value = new BigDecimal(otherData.getV());
                } catch (Exception e) {
                }
                if (value != null) {
                    BigDecimal showRangeUp = showDataItem_up.get(f);
                    BigDecimal showRangeLow = showDataItem_low.get(f);
                    if (showRangeUp != null && showRangeUp.compareTo(value) < 0) {
                        // 大于最大值
                    } else if (showRangeUp != null && showRangeLow.compareTo(value) > 0) {
                        // 小于最小值
                    } else {
                        mapData.put(f, otherData.getS());
                        mapData.put(f + "_V", otherData.getV());
                    }
                } else {
                    mapData.put(f, otherData.getS());
                    mapData.put(f + "_V", otherData.getV());
                }
            }
        }

     /*   //判断历史数据所有数据项 数据是否为0
        for (GetFieldDtoListDto getFieldDtoListDto : fieldDtoList) {
            String dataItem = getFieldDtoListDto.getDataItem();
            getFieldDtoListDto.setIsShowData(false);
            for (Map<String, Object> map : dataList) {
                if (map.get(dataItem) != "0"){
                    getFieldDtoListDto.setIsShowData(true);
                    break;
                }
            }
        }*/


        // modify by zhouy 20
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", vo.getStartTime());
        map.put("endTime", vo.getEndTime());
        res.setData(map);


        res.setPageid(vo.getPageid());
        res.setPagesize(vo.getPagesize());
        res.setDatas(classifyDtoList);
        res.setPage(dataList);
        res.setExtData(fieldDtoList);
        res.setRetCode(0);
        res.setRetMessage("OK");
        return res;
    }

    @Override
    public Integer saveEquipmentInfo(IsEquipmentInfo isEquipmentInfo) throws SQLException {
        Integer res = 0;
        if (ObjectUtil.isNull(isEquipmentInfo.getId())) {
            //            isEquipmentInfo.setSbId(DBUtils.getDjbh(isEquipmentInfo.getManufactureId(), "SB_"));
            isEquipmentInfo.setSbId("SB_" + IdUtils.getIncreaseIdByNanoTime());
            isEquipmentInfo.setCjsj(new Date());

            // 补充必填参数,但是现在没有,先保存默认值
            isEquipmentInfo.setHtbh("");
            isEquipmentInfo.setSjly("agent");
            isEquipmentInfo.setIsOpen(0);
            res = this.baseMapper.insert(isEquipmentInfo);
        } else {
            isEquipmentInfo.setXgsj(new Date());
            res = this.baseMapper.updateById(isEquipmentInfo);
        }
        return res;
    }

    /**
     * 安装工单派单生成设备信息
     */
    @Override
    public String saveWorkOrderEquipmentInfo(SaveWorkOrderEquipmentInfoBO bo) throws Exception {
        String sbId = StrUtil.EMPTY;
        // 查询系统单详情
        SalePriceMasterDTO priceSheetDetail = salePriceService.getPriceSheetDetail(bo.getPriceMasterId());
        if (ObjectUtil.isNull(priceSheetDetail)) {
            return sbId;
        }
        // 获取安装工单产品信息
        List<SalePriceDetailDTO> childList = priceSheetDetail.getChildList();
        if (CollectionUtil.isEmpty(childList)) {
            return sbId;
        }
        // 生成安装工单设备信息
        for (SalePriceDetailDTO item : childList) {
            Integer count = item.getCount(); // 产品数量
            String equipmentId = item.getEquipmentId(); // 设备类型id
            if (StrUtil.isBlank(equipmentId)) {
                continue;
            }
            for (int i = 0; i < count; i++) {
                IsEquipmentInfo isEquipmentInfo = new IsEquipmentInfo();
                //                isEquipmentInfo.setSbId(DBUtils.getDjbh(bo.getOperateUserCompanyId(), "SB_")); // 【设备】首字母开头
                // 舍弃上面的id生成方式，多线程环境下不能保证全局唯一
                isEquipmentInfo.setSbId("SB_" + IdUtils.getIncreaseIdByNanoTime()); // 【设备】首字母开头
                if (CompanyTypeEnum._00.getKey()
                        .equals(bo.getOperateUserCompanyType()) || CompanyTypeEnum._01.getValue()
                        .equals(bo.getOperateUserCompanyType())) {
                    isEquipmentInfo.setManufactureId(bo.getUserInfo().getNes_companyId());
                    isEquipmentInfo.setSblxId(equipmentId);
                } else {
                    // 找代理商的厂家，通过设备类型ID + 代理关系 确定出厂家ID
                    setEquipmentField(equipmentId, bo, isEquipmentInfo);
                }
                isEquipmentInfo.setScddh(String.valueOf(bo.getSaleOrderId()));
                isEquipmentInfo.setBdzt(0);
                isEquipmentInfo.setBz("安装工单派单生成设备");
                isEquipmentInfo.setSfsc(0);
                isEquipmentInfo.setCjsj(bo.getOperateDate());
                isEquipmentInfo.setXgsj(bo.getOperateDate());
                isEquipmentInfo.setAlias(item.getEquipmentName());
                isEquipmentInfo.setUpOper(String.valueOf(bo.getOperateUserId()));
                isEquipmentInfo.setCreateOper(String.valueOf(bo.getOperateUserId()));
                isEquipmentInfo.setWorkOrderId(bo.getWorkOrderId());
                isEquipmentInfo.setDdId(bo.getCustomerHouseId());
                // 补充必填参数,但是现在没有,先保存默认值
                isEquipmentInfo.setHtbh("");
                isEquipmentInfo.setSjly("agent");
                isEquipmentInfo.setIsOpen(0);

                Integer rows = this.baseMapper.insert(isEquipmentInfo);
                if (1 != rows) {
                    throw new Exception("保存设备信息失败!");
                }
                sbId = isEquipmentInfo.getSbId();
            }
        }
        return sbId;
    }

    // 获取设备的厂商id
    private void setEquipmentField(String equipmentId, SaveWorkOrderEquipmentInfoBO bo,
            IsEquipmentInfo isEquipmentInfo) throws Exception {
        isEquipmentInfo.setSblxId(equipmentId);
        isEquipmentInfo.setManufactureId(bo.getUserInfo().getNes_companyId());
        isEquipmentInfo.setAgentId(bo.getUserInfo().getNes_companyId());
        // 查询代理的厂商公司id
        List<String> manufacturerCompanyIdList = tAgentFacturerMapper.getManufacturerCompanyIdList(bo.getOperateUserCompanyId());

        // 如果没有代理的厂商，设备记录自己的公司id
        if (CollectionUtil.isEmpty(manufacturerCompanyIdList)) {
            return;
        }

        // 查询设备型号
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("sblx", equipmentId);
        GGoods goods = gGoodsService.getOne(wrapper);
        if (ObjectUtil.isNull(goods)) {
            return;
        }
        String goodsCode = goods.getGoodsCode();

        /**
         * 根据当前代理商代理的厂商数量，做不同的处理
         * 如果有厂商，需要判断这些厂商是否维护了目标设备的信息
         * 如果没有任何厂商维护目标设备,说明该设备属于代理商自己创建的
         * 如果只有一个厂商维护目标设备，说明该设备属于这一个厂商
         * 如果有多个厂商维护目标设备，就使用品牌id再次确定厂商公司id
         */
        List<Map<String, String>> equipmentInfoList = sblxService.getManufacturerEquipmentInfo(goodsCode, manufacturerCompanyIdList);

        if (CollectionUtil.isNotEmpty(equipmentInfoList)) {
            for (Map<String, String> map : equipmentInfoList) {
                Company company = businessCompanyService.getCompany(map.get("companyId"));
                if (ObjectUtil.isNotNull(company)) {
                    isEquipmentInfo.setSblxId(map.get("sblxId"));
                    isEquipmentInfo.setManufactureId(company.getNesCompanyid());
                    return;
                }
            }
        }
    }

    @Override
    public List<EquipmentInfoDTO> getEquipmentInfoListByWorkOrderId(Long workOrderId) {
        List<IsEquipmentInfo> equipmentInfoList = this.baseMapper.getEquipmentInfoListByWorkOrderId(workOrderId);
        List<EquipmentInfoDTO> equipmentInfoDTOList = CopyUtils.copyList(equipmentInfoList, EquipmentInfoDTO.class);
        // 设置返回参数
        equipmentInfoDTOList.forEach(item -> {
            try {
                GGoodsDTO goodsDetail = gGoodsService.getGoodsDetailBySblx(item.getSblxId());
                item.setSblxName(goodsDetail.getGoodsName());
                item.setBrandName(goodsDetail.getBrandName());
                item.setUnitName(goodsDetail.getUnitName());
                item.setEnergyTypeName(goodsDetail.getEnergyTypeName());
                item.setEquipmentModel(goodsDetail.getGoodsCode());
                item.setDeviceSerialNumber(item.getSbxlh());
                item.setManufactureId(StrUtil.isBlank(item.getAgentId()) ? item.getManufactureId() : item.getAgentId());
            } catch (Exception e) {
                log.info("查询设备相关信息失败,错误原因:{}", e.getMessage());
            }
        });
        return equipmentInfoDTOList;
    }

    @Override
    public List<EquipmentInfoDTO> getEquipmentInfoListByDDid(String ddid) {
        List<IsEquipmentInfo> equipmentInfoList = this.baseMapper.getEquipmentInfoListByDDid(ddid);
        List<EquipmentInfoDTO> equipmentInfoDTOList = CopyUtils.copyList(equipmentInfoList, EquipmentInfoDTO.class);
        // 设置返回参数
        equipmentInfoDTOList.forEach(item -> {
            try {
                GGoodsDTO goodsDetail = gGoodsService.getGoodsDetailBySblx(item.getSblxId());
                item.setSblxName(goodsDetail.getGoodsName());
                item.setBrandName(goodsDetail.getBrandName());
                item.setUnitName(goodsDetail.getUnitName());
                item.setEnergyTypeName(goodsDetail.getEnergyTypeName());
                item.setEquipmentModel(goodsDetail.getGoodsCode());
                item.setDeviceSerialNumber(item.getSbxlh());
                item.setManufactureId(StrUtil.isBlank(item.getAgentId()) ? item.getManufactureId() : item.getAgentId());
            } catch (Exception e) {
                log.info("查询设备相关信息失败,错误原因:{}", e.getMessage());
            }
        });
        return equipmentInfoDTOList;
    }

    @Override
    public List<EquipmentInfoDTO> getEquipmentInfoS(String equipmentIds) throws Exception {
        List<IsEquipmentInfo> equipmentInfoList = this.baseMapper.getEquipmentInfoS(equipmentIds);
        List<EquipmentInfoDTO> equipmentInfoDTOList = null;
        if (ObjectUtil.isNotNull(equipmentInfoList)) {
            equipmentInfoDTOList = CopyUtils.copyList(equipmentInfoList, EquipmentInfoDTO.class);
        } else {
            throw new Exception("查询设备失败!");
        }
        return equipmentInfoDTOList;
    }

    @Override
    public void delEquipmentInfoById(Long id) {
        IsEquipmentInfo isEquipmentInfo = new IsEquipmentInfo();
        isEquipmentInfo.setId(id);
        isEquipmentInfo.setSfsc(1);
        this.baseMapper.updateById(isEquipmentInfo);
    }

    @Override
    public List<EquipmentDTO> getEquipmentList(EquipmentBO bo) throws Exception {
        List<IsEquipmentInfo> equipmentInfoList = this.baseMapper.selectList(buildEquipmentBaseQueryWarpper(bo));
        if (CollUtil.isEmpty(equipmentInfoList)) {
            return Collections.emptyList();
        }

        // 查询设备型号
        List<String> queryDeviceModelList = equipmentInfoList.stream()
                .map(IsEquipmentInfo::getSblxId)
                .collect(Collectors.toList());
        List<Sblx> deviceModelList = sblxService.getDeviceModels(queryDeviceModelList);
        Map<String, Sblx> deviceModelMap = new HashMap<>();
        if (CollUtil.isNotEmpty(deviceModelList)) {
            deviceModelMap.putAll(deviceModelList.stream().collect(Collectors.toMap(Sblx::getSblxId, sblx -> sblx)));
        }

        // 查询设备厂家
        List<String> queryManufactureList = equipmentInfoList.stream()
                .map(IsEquipmentInfo::getManufactureId)
                .collect(Collectors.toList());
        List<IsManufactureInfo> manufactureInfoList = manufactureService.getManufactures(queryManufactureList);
        Map<String, IsManufactureInfo> manufactureInfoMap = new HashMap<>();
        if (CollUtil.isNotEmpty(manufactureInfoList)) {
            manufactureInfoMap.putAll(manufactureInfoList.stream()
                    .collect(Collectors.toMap(IsManufactureInfo::getManufactureId, manufactureInfo -> manufactureInfo)));
        }

        List<EquipmentDTO> equipmentDTOList = new ArrayList<>();
        for (IsEquipmentInfo isEquipmentInfo : equipmentInfoList) {
            EquipmentDTO equipmentDTO = EquipmentDTO.from(isEquipmentInfo);
            if (deviceModelMap.containsKey(equipmentDTO.getEquipmentModelId())) {
                equipmentDTO.setEquipmentModelName(deviceModelMap.get(equipmentDTO.getEquipmentModelId()).getSbmc());
            }
            if (manufactureInfoMap.containsKey(equipmentDTO.getManufactureId())) {
                equipmentDTO.setManufactureName(manufactureInfoMap.get(equipmentDTO.getManufactureId()).getName());
            }
            equipmentDTOList.add(equipmentDTO);

        }

        return equipmentDTOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delEquipmentInfoByWorkOrderId(List<Long> workOrderIdList, Date operateDate, Long operateUserId) {
        if (CollectionUtil.isEmpty(workOrderIdList)) {
            throw new MissBusinessParameterException("workOrderIdList must not empty");
        }

        QueryWrapper<IsEquipmentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("sfsc", DeleteEnum._0.getKey());
        wrapper.in("work_order_id", workOrderIdList);

        IsEquipmentInfo isEquipmentInfo = new IsEquipmentInfo();
        isEquipmentInfo.setSfsc(DeleteEnum._1.getKey());
        isEquipmentInfo.setXgsj(operateDate);
        isEquipmentInfo.setUpOper(String.valueOf(operateUserId));

        Integer rows = this.baseMapper.update(isEquipmentInfo, wrapper);
        if (rows <= 0) {
            throw new IllegalBusinessException("删除设备信息失败");
        }
    }

    private QueryWrapper<IsEquipmentInfo> buildEquipmentBaseQueryWarpper(EquipmentBO bo) {
        QueryWrapper<IsEquipmentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sfsc", DeleteEnum._0.getKey());
        if (StrUtil.isNotEmpty(bo.getEquipmentId())) {
            queryWrapper.eq("sb_id", bo.getEquipmentId());
        }
        if (StrUtil.isNotEmpty(bo.getManufacturerId())) {
            queryWrapper.eq("manufacture_id", bo.getManufacturerId());
        }
        if (StrUtil.isNotEmpty(bo.getEquipmentModelId())) {
            queryWrapper.eq("sblx_id", bo.getEquipmentModelId());
        }
        if (StrUtil.isNotEmpty(bo.getEqDtuId())) {
            queryWrapper.eq("wx_id", bo.getEqDtuId());
        }
        if (StrUtil.isNotEmpty(bo.getLikeDtuId())) {
            queryWrapper.like("wx_id", bo.getLikeDtuId());
        }
        return queryWrapper;
    }

    /**
     * @param sbId   设备ID
     * @param offset 减去天数
     */
    private String[] getLastHisDateBySbID(String sbId, String offset) {
        String[] lastTime = new String[2];
        lastTime[0] = DBUtils.getDate(-2) + " 00:00:00";
        lastTime[1] = DBUtils.getDate(0) + " 23:59:59";
        List<GetLastHisDateBySbIDDto> dataList = isNormDataHisBufferMapper.getLastHisDateBySbID(sbId, offset);
        if (dataList.size() > 0) {
            String gmtcreateEnd = dataList.get(0).getGmtcreateEnd();
            if (StrUtil.isNotEmpty(gmtcreateEnd) && !gmtcreateEnd.equals("0000-00-00 00:00:00")) {
                lastTime[0] = dataList.get(0).getGmtcreate();
            }
        }
        return lastTime;
    }

    /**
     * 查询数据项显示对勾字段
     */
    private Map<String, Object> getProtocolDataItem(String protocolId, Long operateUserId) {
        Map<String, Object> map = new HashMap<>();
        //先查询记忆表 如果无数据查询默认表
        List<ProtocolDataItemMemory> protocolDataItemMemories = protocolDataItemMemoryMapper.selectList(new QueryWrapper<ProtocolDataItemMemory>().eq(ProtocolDataItemMemory.PROTOCOL_ID, protocolId)
                .eq(ProtocolDataItemMemory.USER_ID, operateUserId));
        if (protocolDataItemMemories == null || protocolDataItemMemories.size() == 0) {
            //查询默认表
            List<IsSystemStandardField> protocolDataItemDefaultList = isSystemStandardFieldMapper.selectList(new QueryWrapper<IsSystemStandardField>().eq("deleted", 0));
            if (protocolDataItemDefaultList != null && protocolDataItemDefaultList.size() > 0) {
                //转为map
                map = protocolDataItemDefaultList.stream()
                        .collect(Collectors.toMap(IsSystemStandardField -> IsSystemStandardField.getField(), IsSystemStandardField -> IsSystemStandardField.getName()));
            }
        } else {
            //转为map
            String codes = protocolDataItemMemories.get(0).getCodes();
            String[] split = codes.split(";");
            map = Arrays.stream(split).collect(Collectors.toMap(key -> key, key -> key));
        }
        return map;
    }

}
